package com.hex.ds.em.hcdp.gauss.analyze.script.performance;


import static com.hex.ds.em.hcdp.gauss.pack.service.impl.ScriptPackTaskServiceImpl.wordResult;

import com.hex.ds.em.hcdp.basic.common.IResultForReport;
import com.hex.ds.em.hcdp.gauss.analyze.script.performance.entity.CheckEndStatisticalTableEntity;
import com.hex.ds.em.hcdp.gauss.common.entity.ScriptPackScanResultEntity;
import com.hex.ds.em.hcdp.gauss.common.enums.AntlrEnum;
import com.hex.hlrt.gauss.g4.basic.gen.GaussParser;
import com.hex.hlrt.gauss.g4.basic.gen.GaussParser.AnalyzeContext;
import com.hex.hlrt.gauss.g4.basic.gen.GaussParser.Sql_scriptContext;
import com.hex.hlrt.gauss.g4.basic.gen.GaussParserBaseListener;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @Package com.hex.ds.em.hcdp.impala.analyze.script.performance
 * @ClassName CheckEndStatisticalTableListener
 * @Description 检查程序尾部是否做了统计表信息操作
 * @Author gj.xu
 * @Date 2024/9/13 18:46
 * @Version v2.0
 **/
@Slf4j
@Accessors(chain = true)
@Scope(value = "prototype")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Service("Gauss-CheckEndStatisticalTable")
public class CheckEndStatisticalTableListener extends GaussParserBaseListener implements
    IResultForReport {

  CheckEndStatisticalTableEntity ruleEntity = new CheckEndStatisticalTableEntity();

  @Override
  public void exitCreate_table(GaussParser.Create_tableContext ctx) {
    ruleEntity.addRuleMark(ctx.table_name().getText().trim());
  }

  @Override
  public void exitAnalyze(AnalyzeContext ctx){
    ruleEntity.ifExistRemoveTable(ctx.tableview_name().getText().trim());
  }

  @Override
  public void enterSql_script(GaussParser.Sql_scriptContext ctx) {
    // 初始化
    ruleEntity = new CheckEndStatisticalTableEntity();
  }

  @Override
  public void exitSql_script(Sql_scriptContext ctx) {
    if (ruleEntity.tables.size() > 0) {
      // 更新扫描后word指标结果
      setResultForWordReport();

      ctx.addAnyChild(ruleEntity);
      log.info("rule-[CheckEndStatisticalTable]:");
    }
  }

  @Override
  public void setResultForWordReport() {
    ScriptPackScanResultEntity result = wordResult.get(AntlrEnum.END_STATISTICAL_TABLE_CHECK.getValue());
    if (result == null) {
      return;
    }
    result.setScanTable("").setScanState("fail");
    wordResult.put(AntlrEnum.END_STATISTICAL_TABLE_CHECK.getValue(), result);
  }

}
